// 引入创建store的函数,和创建slice的函数
import { configureStore, createSlice, createAsyncThunk } from '@reduxjs/toolkit'

// 创建Count组件的异步的代码
export const asyncCount = createAsyncThunk('yyy', () => {
  return new Promise<number>((resolve, reject) => {
    setTimeout(() => {
      resolve(3)
      // reject('123')
    }, 1000)
  })
})
// 创建List组件的异步的代码
export const asyncList = createAsyncThunk('zzz', () => {
  return new Promise<string>((resolve, reject) => {
    setTimeout(() => {
      resolve('d')
      // reject('123')
    }, 1000)
  })
})
// 先创建count组件对应的slice
// 注意: 一般一个组件需要操作redux的数据,就会给这个组件创建一个对应的slice
const countSlice = createSlice({
  name: 'count',
  initialState: { c: 0, msg: 'hello world' },
  reducers: {
    // 这个state并不是redux中完整的state,其实是state中属于当前slice的那一份数据
    add(state, action) {
      state.c = state.c + 1
    },
    sub(state, action) {
      state.c = state.c - action.payload
    },
  },
  // 新增代码:
  // 为异步操作定义action
  extraReducers(builder) {
    // builder.addCase(asyncCount.pending, () => {
    //   console.log('正在异步操作')
    // })
    builder.addCase(asyncCount.fulfilled, (state, action) => {
      console.log('成功', state, action)
      state.c = state.c * action.payload
    })
    // builder.addCase(asyncCount.rejected, (state, action) => {
    //   console.log('失败')
    // })
  },
})

// 创建list组件对应的slice
const listSlice = createSlice({
  name: 'list',
  initialState: ['a', 'b', 'c'],
  reducers: {
    insert(state, action) {
      state.push(action.payload)
    },
  },
  // 新增代码:
  // 为异步操作定义action
  extraReducers(builder) {
    builder.addCase(asyncList.pending, () => {
      console.log('正在异步操作')
    })
    builder.addCase(asyncList.fulfilled, (state, action) => {
      state.push(action.payload)
    })
    builder.addCase(asyncList.rejected, (state, action) => {
      console.log('失败')
    })
  },
})
// 创建store
// 注意:创建store的时候需要配置slice
const store = configureStore({
  // reducer属性是固定的
  reducer: {
    // count是随意起的属性名
    count: countSlice.reducer,
    list: listSlice.reducer,
  },
})

export default store
// 导出slice中自动帮我们创建的actionCreator
export const { add, sub } = countSlice.actions
export const { insert } = listSlice.actions
// console.log('初始数据', store.getState())
// store.subscribe(() => {
//   console.log('修改之后的数据', store.getState())
// })

// store.dispatch({ type: 'count/add' })

export type RootState = ReturnType<typeof store.getState> //解决获取状态时,ts编译错误
export type AppDispatch = typeof store.dispatch // 解决异步操作时dispatch位置的ts编译错误
